<?php
/**
 * 用户模型
 * @author sundongdong
 *
 */
class System_Model_User extends Model_Base {
	/**
	 * 获取用户信息
	 * @param number $user_id
	 */
	public function getUserinfo($user_id=0){
		return $this->db()->fetchRow("select * from `s_user` where user_id=:user_id", array('user_id'=>$user_id));
	}
	/**
	 * 获取所有角色
	 */
	public function getAllRoles() {
		return $this->db()->fetchAll("select * from `s_role`");
	}
	/**
	 * 获取所有分类
	 * @param string $lang
	 * @param string $open
	 */
	public function getAllCategorys($lang='name_ch', $open='true') {
		return $this->db()->fetchAll("select id,$lang as name, parent_id as pId,'$open' as open from p_product_catalog where is_enable=1 order by order_id");
	}
	/**
	 * 获取所有仓库
	 * @param string $lang
	 * @param string $open
	 */
	public function getAllWares($lang='warehouse_name', $open='true', $other_id=-6) {
		$warehouses = $this->db()->fetchAll("select id,$lang as name,case dept_id when dept_id then -dept_id else $other_id end as pId,'$open' as open from `c_warehouse`");
		$depts = $this->db()->fetchAll("select -id as id,department_name as name,0 as Pid,'$open' as open from `c_warehouse_dept`");
		$depts[] = array('id'=>$other_id,'name'=>'其他','Pid'=>0,'open'=>$open);
		return array_merge($warehouses, $depts);
	}
	/**
	 * 获取指定用户的角色权限
	 * @param number $user_id
	 */
	public function getUserRoles($user_id=0) {
		return $this->db()->fetchAll("select * from s_user_role where user_id=:user_id", array('user_id'=>$user_id));
	}
	/**
	 * 获取指定用户的分类权限
	 * @param number $user_id
	 */
	public function getUserCates($user_id=0) {
		return $this->db()->fetchAll("select * from s_user_category where user_id=:user_id", array('user_id'=>$user_id));
	}
	/**
	 * 获取指定用户的仓库权限
	 * @param number $user_id
	 */
	public function getUserWares($user_id=0) {
		return $this->db()->fetchAll("select * from s_user_warehouse where user_id=:user_id", array('user_id'=>$user_id));
	}
	/**
	 * 更新用户的权限
	 * @param number $user_id
	 * @param array $data
	 * @param string $user_name
	 * @return number[]|string[]|number[]|NULL[]
	 */
	public function setUserPrivilige($user_id=0,array $data,$user_name='system') {
		try {
			$this->db("write_db")->beginTransaction();
			// 删除原来的权限
			$this->db('write_db')->delete('s_user_role', 'user_id='.$user_id);
			$this->db('write_db')->delete('s_user_category', 'user_id='.$user_id);
			$this->db('write_db')->delete('s_user_warehouse', 'user_id='.$user_id);
			// 更新权限
			$roles = array();
			foreach ($data['roles'] as $role) {
				$roles[] = array(
					'user_id' => $user_id,
					'role_id' => $role,
					'update_user' => $user_name
				);
			}
			$this->insertBatch($this->db('write_db'), 's_user_role', $roles);
			$cates = array();
			foreach ($data['cates'] as $cate) {
				$cates[] = array(
					'user_id' => $user_id,
					'category_id' => $cate,
					'update_user' => $user_name
				);
			}
			$this->insertBatch($this->db('write_db'), 's_user_category', $cates);
			$wares = array();
			foreach ($data['wares'] as $ware) {
				$wares[] = array(
					'user_id' => $user_id,
					'warehouse_id' => $ware,
					'update_user' => $user_name
				);
			}
			$this->insertBatch($this->db('write_db'), 's_user_warehouse', $wares);
			// 更新用户表
			$this->db('write_db')->update('s_user', array('update_user' => $user_name, 'update_time'=>date('Y-m-d H:i:s')), 'user_id='.$user_id);
			$this->db('write_db')->commit();
			return array('status'=>1, 'content'=>"更新成功");
		} catch (Exception $e) {
			$this->db('write_db')->rollBack();
			return array('status'=>0, 'content'=>$e->getMessage());
		}
	}
	/**
	 * 获取用户列表
	 * @param array $params
	 * @param number $user_id
	 */
	public function getUserList(array $params, $user_id=0) {
		$where = ' where 1 ';
		$form_add = '';
		$datas = array();
		if ($params['keyword'] != '') {
			$where .= " and (u.user_name like :user_name) or (u.real_name like :user_name)";
			$datas['user_name'] = "%".$params['keyword']."%";
		}
		if ($params['role_id'] != '') {
			$form_add .= ",s_user_role as ur";
			$where .= " and ur.user_id=u.user_id and ur.role_id=:role_id";
			$datas['role_id'] = $params['role_id'];
		}
		if ($params['select_cat_id'] != '') {
			$form_add .= ",s_user_category as uc";
			$where .= " and uc.user_id=u.user_id and uc.category_id=:category_id";
			$datas['category_id'] = $params['select_cat_id'];
		}
		if ($params['select_dept_id'] != '') {
			$where .= " and u.department_id IN(".$this->getChildDepartment($params['select_dept_id']).")";
		}
		if ($params['is_group_leader'] != '') {
			$where .= " and u.is_group_leader = :is_group_leader";
			$datas['is_group_leader'] = $params['is_group_leader'];
		}
		if ($params['is_enable'] != '') {
			$where .= " and u.is_enable = :is_enable";
			$datas['is_enable'] = $params['is_enable'];
		}
		$countsql = "select count(1) from `s_user` u ". $form_add . $where;
		$sql = "select u.* from `s_user` as u " . $form_add . $where . " order by user_id";
		$sql = $sql.' limit '.($params['page'] - 1)*$params['perPage'].','.$params['perPage'];
		
		$count = $this->db()->fetchOne($countsql, $datas);
		$list = $this->db()->fetchAll($sql, $datas);
		foreach ($list as $key => $val) {
			// 部门名称格式化
			$list[$key]['detp_name'] = $this->getDeptBread($val['department_id']);
			// 角色名称格式化
			$list[$key]['role_name'] = $this->getUserRoleBread($val['user_id']);
		}
		$data['totalCounts'] = $count;
		$data['list'] = $list;
		
		return $data;
	}
	/**
	 * 获取用户的权限文字
	 * @param number $user_id
	 */
	public function getUserRoleBread($user_id=0) {
		$roles = $this->db()->fetchPairs("select id,role_name from s_user_role ur left join s_role r using(role_id) where user_id=:user_id", array('user_id'=>$user_id));
		return implode(',', $roles);
	}
	/**
	 * 获取部门子集
	 * @param number $parent_id
	 */
	public function getChildDepartment($parent_id=0) {
		$str = (string)$parent_id;
		$department_ids = $this->db()->fetchPairs("SELECT department_id as id,department_name as department FROM s_department WHERE parent_id={$parent_id}");
		if($department_ids)
		{
			foreach($department_ids as $department_id => $department)
			{
				$temp = $this->getChildDepartment($department_id);
				if($temp)
				{
					$str = $temp . ',' . $str;
				}
			}
		}
		return $str;
	}
	/**
	 * 获取分类的父类
	 * @param unknown $category_id
	 * @return string|unknown
	 */
	public function getCategoryParents($category_id) {
		$string = "";
		if(strlen($category_id) > 0) {
			$row = $this->db()->fetchRow("select parent_id from p_product_catalog where id=:id", array('id'=>$category_id));
			$string = $category_id;
			if ($row && $row['parent_id'] != 0) {
				$t_str = $this->getCategoryParents($row['parent_id']);
				$string = $t_str . ',' . $string;
			}
		}
		return $string;
	}
	/**
	 * 
	 * @param unknown $dept_id
	 */
	public function getDepartmentParents($dept_id) {
		$str = '';
		if ($dept_id) {
			$parent_id = $this->db()->fetchOne('select parent_id from s_department where department_id=:id', array('id'=>$dept_id));
			$str = (string)$dept_id;
			if($parent_id) {
				$temp = $this->getDepartmentParents($parent_id);
				$str = $temp . ',' . $str;
			}
		}
		return $str;
	}
	/**
	 * 获取部门面包屑 物流部>采购组>2组
	 * @param unknown $dept_id
	 * @return string|unknown
	 */
	public function getDeptBread($dept_id)
	{
		$deptBread = '';
		$deptInfo = $this->db()->fetchRow("select parent_id,department_name from `s_department` where department_id=:id",array("id"=>$dept_id));
		$deptBread .= $deptInfo['department_name'];
		if($deptInfo['parent_id']>0){
			$deptBread = $this->getDeptBread($deptInfo['parent_id']).' > '.$deptBread;
		}
		return $deptBread;
	}
	/**
	 * 根据父ID获取分类
	 * @param number $cat_id
	 */
	public function getCategory($cat_id=0) {
		return $this->db()->fetchAll("select id,name_en,name_ch as name from `p_product_catalog` where parent_id = $cat_id and is_enable=1 order by order_id ");
	}
	/**
	 * 根据父ID获取部门
	 * @param number $dept_id
	 */
	public function getDepart($dept_id=0) {
		return $this->db()->fetchAll("SELECT department_id as id,department_name AS name FROM `s_department` WHERE parent_id = $dept_id ");
	}
}